package com.movitech.mobile.cz.base.bizconfig.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.movitech.mobile.cz.base.bizconfig.entity.SSuppliersCategory;
import com.movitech.mobile.cz.base.bizconfig.entity.SSuppliersCategoryTemplate;
import com.movitech.mobile.cz.base.bizconfig.entity.ext.ExtSSuppliersCategoryTemplate;
import com.movitech.mobile.cz.base.bizconfig.mapper.SSuppliersCategoryTemplateMapper;
import com.movitech.mobile.cz.base.bizconfig.mapper.ext.ExtSSuppliersCategoryTemplateMapper;
import com.movitech.mobile.cz.base.bizconfig.service.SSuppliersCategoryService;
import com.movitech.mobile.cz.base.bizconfig.service.SSuppliersCategoryTemplateService;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.ListObjCopyUtil;
import com.movitech.mobile.cz.base.common.util.PageCode;
import com.movitech.mobile.cz.base.common.utils.StringUtils;
import com.movitech.mobile.cz.base.modules.config.SuppliersCategoryTemplateTypeEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.sys.bizvo.*;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 供应商分类--模板设置 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-02-28
 */
@Service("sSuppliersCategoryTemplateService")
@Transactional
public class SSuppliersCategoryTemplateServiceImpl extends ServiceImpl<SSuppliersCategoryTemplateMapper, SSuppliersCategoryTemplate> implements SSuppliersCategoryTemplateService {

    @Autowired
    private ExtSSuppliersCategoryTemplateMapper extSSuppliersCategoryTemplateMapper;
    @Autowired
    private SSuppliersCategoryService sSuppliersCategoryService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = { "RuntimeException", "Exception" })
    public RestReturnResult<Object> saveOrUpdateSuppliersCategoryTemplate(
            SuppliersCategoryTemplateVO suppliersCategoryTemplateVO) {
        RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);
        try{
            if(suppliersCategoryTemplateVO==null||suppliersCategoryTemplateVO.getTemplateType()==null
                    ||StringUtils.isEmpty(suppliersCategoryTemplateVO.getCategoryId())){
                throw new RuntimeException("参数错误");
            }

            SSuppliersCategory sSuppliersCategory = sSuppliersCategoryService.selectById(suppliersCategoryTemplateVO.getCategoryId());
            List<SuppliersCategoryTemplateRequestVO> suppliersCategoryTemplateRequestVOList=suppliersCategoryTemplateVO.getSuppliersCategoryTemplateRequestVOList();
            Integer updateFlag=CommonConstants.YES_INTEGER;
            if(suppliersCategoryTemplateRequestVOList==null||suppliersCategoryTemplateRequestVOList.size()==0){
                updateFlag=CommonConstants.NO_INTEGER;
            }
            Integer templateType=suppliersCategoryTemplateVO.getTemplateType();

            if (CommonConstants.TEMPLATE_CATEGORY_1 == templateType) {//现场考察
                sSuppliersCategory.setSiteInspectionSetFlag(updateFlag);
            } else if (CommonConstants.TEMPLATE_CATEGORY_2 == templateType) {//履约过程评估
                sSuppliersCategory.setPerformEvalProcSetFlag(updateFlag);

            } else if (CommonConstants.TEMPLATE_CATEGORY_3 == templateType) {//履约后评估
                sSuppliersCategory.setPerformEvalPostSetFlag(updateFlag);

            } else if (CommonConstants.TEMPLATE_CATEGORY_4 == templateType) {//评分定级
                sSuppliersCategory.setEvaluateScoreSetFlag(updateFlag);

            } else if (CommonConstants.TEMPLATE_CATEGORY_5 == templateType) {//技术明标评分
                sSuppliersCategory.setTechnicalScoreSetFlag(updateFlag);

            } else if (CommonConstants.TEMPLATE_CATEGORY_6 == templateType) {//技术暗标评分
                sSuppliersCategory.setTechnicalDarkScoreSetFlag(updateFlag);

            } else if (CommonConstants.TEMPLATE_CATEGORY_7 == templateType) {//项目经理面试评分
                sSuppliersCategory.setPmInterviewScoreSetFlag(updateFlag);
            } else { //模版类型不存在
                hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[5], CommonConstants.ERROR_DESCS[5]);
                return hResult;
            }
            //更新分类信息
            if(!sSuppliersCategoryService.updateById(sSuppliersCategory)){
                throw new RuntimeException("系统错误");
            }
            EntityWrapper wrapper = new EntityWrapper<>();
            SSuppliersCategoryTemplate suppliersCategoryTemplate = new SSuppliersCategoryTemplate();
            suppliersCategoryTemplate.setCategoryId(suppliersCategoryTemplateVO.getCategoryId());
            suppliersCategoryTemplate.setTemplateType(templateType);
            wrapper.setEntity(suppliersCategoryTemplate);
            if(!this.delete(wrapper)){
                throw new RuntimeException("系统错误");
            }
            if (suppliersCategoryTemplateRequestVOList != null && suppliersCategoryTemplateRequestVOList.size() > 0) {
                List<SSuppliersCategoryTemplate> ls=ListObjCopyUtil.copyTo(suppliersCategoryTemplateRequestVOList,SSuppliersCategoryTemplate.class);
                for(SSuppliersCategoryTemplate obj:ls){
                    obj.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
                }
                //更新模板信息
                if(!this.insertOrUpdateBatch(ls)){
                    throw new RuntimeException("系统错误");
                }
            }
            hResult=RestReturnResult.success();
        }catch (Exception e){
            e.printStackTrace();
            hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
        }
        return hResult;
    }

    @Override
    public RestReturnResult<Object> updateSuppliersCategoryTemplateForDel(String id) {
        RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        if (StringUtils.isNotEmpty(id)) {

            SSuppliersCategoryTemplate suppliersCategoryTemplate = baseMapper.selectById(id);

            if (suppliersCategoryTemplate != null) {

                suppliersCategoryTemplate.setDelFlag(CommonConstants.YES_INTEGER);

                Date updateDate = new Date();
                String userId = UserUtils.getCurrentUserId();
                suppliersCategoryTemplate.setUpdateBy(userId);
                suppliersCategoryTemplate.setUpdateDate(updateDate);

                baseMapper.updateById(suppliersCategoryTemplate);

                hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[2], CommonConstants.SUCCESS_DESCS[2]);

            } else {//数据不存在
                hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
            }

        } else {
            hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
        }

        return hResult;
    }

    @Override
    public RestReturnResult searchSuppliersCategoryTemplateList(SuppliersCategoryTemplateListRequestVO suppliersCategoryTemplateListRequestVO) {
        RestReturnResult<Object> restReturnResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {
            PageCode pageCode = new PageCode(suppliersCategoryTemplateListRequestVO.getPageNumber(), suppliersCategoryTemplateListRequestVO.getPageSize());

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("categoryName", suppliersCategoryTemplateListRequestVO.getSupplierCategoryName());
            map.put("templateType", suppliersCategoryTemplateListRequestVO.getSupplierCategoryTemplateType());

            pageCode.setCount(extSSuppliersCategoryTemplateMapper.searchSuppliersCategoryTemplateListCounts(map));

            map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            map.put("isPage", suppliersCategoryTemplateListRequestVO.getPageFlag());

            List<ExtSSuppliersCategoryTemplate> ls = extSSuppliersCategoryTemplateMapper.searchSuppliersCategoryTemplateList(map);
            List<SuppliersCategoryTemplateListResponseVO> result = this.getSuppliersCategoryTemplateListResponseVO(ls);
            pageCode.setList(result);

            restReturnResult = new RestReturnResult(CommonConstants.SUCCESS, pageCode);
        } catch (Exception e) {
            e.printStackTrace();
            restReturnResult = new RestReturnResult(CommonConstants.FAIL, CommonConstants.ERROR_DESCS[1], CommonConstants.ERROR_CODES[1]);
        }

        return restReturnResult;
    }

    /**
     * 供应商分类模版转换
     *
     * @param list
     * @return
     */
    private List<SuppliersCategoryTemplateListResponseVO> getSuppliersCategoryTemplateListResponseVO(List<ExtSSuppliersCategoryTemplate> list) {
        List<SuppliersCategoryTemplateListResponseVO> result = null;

        if (list != null && list.size() > 0) {
            result = new ArrayList<SuppliersCategoryTemplateListResponseVO>();
            for (ExtSSuppliersCategoryTemplate entity : list) {
                SuppliersCategoryTemplateListResponseVO vo = new SuppliersCategoryTemplateListResponseVO();
                vo.setId(entity.getId());

                String templateName = "";
                String constants = "模版";
                String supplierCategoryName = entity.getSupplierCategoryName();
                int templateType = entity.getTemplateType();

                if (templateType == SuppliersCategoryTemplateTypeEnum.SITE_INSPECTION.getCode()) { //现场考察

                    templateName = supplierCategoryName + SuppliersCategoryTemplateTypeEnum.SITE_INSPECTION.getDesc() + constants;

                } else if (templateType == SuppliersCategoryTemplateTypeEnum.EVALUATE_IMPLEMENTATION_PROCESS.getCode()) { //履约过程评估

                    templateName = supplierCategoryName + SuppliersCategoryTemplateTypeEnum.EVALUATE_IMPLEMENTATION_PROCESS.getDesc() + constants;

                } else if (templateType == SuppliersCategoryTemplateTypeEnum.EVALUATE_IMPLEMENTATION_END.getCode()) { //履约后评估

                    templateName = supplierCategoryName + SuppliersCategoryTemplateTypeEnum.EVALUATE_IMPLEMENTATION_END.getDesc() + constants;

                } else if (templateType == SuppliersCategoryTemplateTypeEnum.SCORE_GRADE.getCode()) { //评分定级

                    templateName = supplierCategoryName + SuppliersCategoryTemplateTypeEnum.SCORE_GRADE.getDesc() + constants;

                } else if (templateType == SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_BRIGHT_MARK.getCode()) { //技术明标评分

                    templateName = supplierCategoryName + SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_BRIGHT_MARK.getDesc() + constants;

                } else if (templateType == SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_DARK_MARK.getCode()) { //技术暗标评分

                    templateName = supplierCategoryName + SuppliersCategoryTemplateTypeEnum.SCORE_TECHNOLOGY_DARK_MARK.getDesc() + constants;

                } else if (templateType == SuppliersCategoryTemplateTypeEnum.SCORE_INTERVIEW_BY_MANAGER.getCode()) { //项目经理面试评分

                    templateName = supplierCategoryName + SuppliersCategoryTemplateTypeEnum.SCORE_INTERVIEW_BY_MANAGER.getDesc() + constants;

                }

                vo.setTemplateName(templateName);

                result.add(vo);
            }
        }

        return result;
    }

    @Override
    public List<SuppliersCategoryTemplateResponseVO> getSuppliersCategoryTemplateDetails(SuppliersCategoryTemplateRequestVO suppliersCategoryTemplateRequestVO) {

        try {

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("categoryId", suppliersCategoryTemplateRequestVO.getCategoryId());
            params.put("templateType", suppliersCategoryTemplateRequestVO.getTemplateType());

            List<ExtSSuppliersCategoryTemplate> list = extSSuppliersCategoryTemplateMapper.getSuppliersCategoryTemplateByCategoryAndType(params);
            List<SuppliersCategoryTemplateResponseVO> result = ListObjCopyUtil.copyTo(list, SuppliersCategoryTemplateResponseVO.class);

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    @Override
    public String getSupplierCategoryTemplateNames(String[] categoryIds,Integer templateType) {
        if (categoryIds == null || categoryIds.length <= 0) {
            return null;
        }
        StringBuffer result = new StringBuffer();
        List<String> list = new ArrayList<>();
        for (String id : categoryIds) {
            list.add(id);
        }
        List<ExtSSuppliersCategoryTemplate> results = extSSuppliersCategoryTemplateMapper.getSupplierCategoryTemplateNames(list,templateType);
        if (results == null || results.size() <= 0) {
            return null;
        }
        int index = 0;
        for (ExtSSuppliersCategoryTemplate template : results) {
            if (index == 0) {
                result.append(template.getEvaluationDimension());
            } else {
                result.append("," + template.getEvaluationDimension());
            }
            index++;
        }
        return result.toString();
    }

    @Override
    public List<SSuppliersCategoryTemplate> selectByCategoryIdAndTypes(String categoryId, Integer... types) {
        return selectList(
                new EntityWrapper<SSuppliersCategoryTemplate>().eq(" del_flag ",CommonConstants.DEL_FLAG_NORMAL)
                        .eq(" category_id ",categoryId).in(" template_type ",types));
    }

}
